// pages/volunteer/my-application.js
const app = getApp()
import api from '../../utils/api'

Page({
  data: {
    list: [],
    page: 1,
    pageSize: 10,
    loading: false,
    hasMore: true
  },

  async onShow() {
    const ok = await app.checkAuth?.()
    if (!ok) return
    this.refresh()
  },

  async refresh() {
    this.setData({ page: 1, hasMore: true })
    await this.loadMore()
  },

  async loadMore() {
    if (this.data.loading || !this.data.hasMore) return
    this.setData({ loading: true })
    try {
      const { page, pageSize } = this.data
      const res = await api.volunteer.getList({ page, page_size: pageSize })
      const items = Array.isArray(res?.list) ? res.list : (Array.isArray(res) ? res : (res?.items || []))
      const merged = page === 1 ? items : this.data.list.concat(items)
      const hasMore = items.length >= pageSize
      this.setData({ list: merged, hasMore, page: page + 1 })
    } catch (e) {
      wx.showToast({ title: e.message || '加载失败', icon: 'none' })
    } finally {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    }
  },

  onPullDownRefresh() {
    this.refresh()
  },

  onReachBottom() {
    this.loadMore()
  },

  async withdraw(e) {
    const { id, index } = e.currentTarget.dataset
    if (!id) return
    wx.showModal({
      title: '撤销确认',
      content: '确定撤销该报名吗？',
      success: async (r) => {
        if (!r.confirm) return
        try {
          await api.volunteer.withdraw(id)
          wx.showToast({ title: '已撤销', icon: 'success' })
          // 从列表移除或刷新
          const list = this.data.list.slice()
          const i = Number(index)
          if (!isNaN(i)) {
            list.splice(i, 1)
            this.setData({ list })
          } else {
            this.refresh()
          }
        } catch (e) {
          wx.showToast({ title: e.message || '撤销失败', icon: 'none' })
        }
      }
    })
  }
})